from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer, BadData


def generate_encrypted_openid(openid):
    """
    生成加密的openid
    参数一：秘钥
    参数二：过期时间
    """
    serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires_in=600)  # 有效期10分钟
    return serializer.dumps({'openid': openid}).decode()


def check_openid(encrypt_openid):
    """校验openid是否合法"""
    sserializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 60 * 10)
    try:
        dict_data = sserializer.loads(encrypt_openid)
    except BadData:  # 签名不合法或者过期
        return None
    else:
        return dict_data.get('openid')